using System;
using System.Threading;
using System.Windows.Forms;
using Comteck.Localization;

namespace Comteck.Winforms.Controls.Loading {
  /// <summary>
  /// 
  /// </summary>
  public class AjaxLoadCursor : IAjaxLoadCommand {
    private class AjaxLoadHidder : IDisposable {
      private readonly IAjaxLoadCommand control;

      public AjaxLoadHidder(IAjaxLoadCommand control) {
        this.control = control;
      }

      public void Dispose() {
        control.HideAjax();
      }
    }
    /// <summary>
    /// 
    /// </summary>
    private readonly Form form = null;
    private readonly AjaxLoadHidder loadHidder;
    private int loadCount = 0;
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="form"></param>
    public AjaxLoadCursor(Form form) {
      this.form = form;
      loadHidder = new AjaxLoadHidder(this);
    }

    /// <summary>
    /// 
    /// </summary>
    public bool IsWork => form.UseWaitCursor;

    /// <inheritdoc/>
    public IDisposable ShowAjax(bool isPrevent = true) {
      if (isPrevent && this.IsWork == true) {
        throw new MultiClickException(BaseResources.MultiClick);
      }
      if (Interlocked.Increment(ref loadCount) == 1) {
        form.UseWaitCursor = true;
        form.Cursor = Cursors.WaitCursor;
      }
      return loadHidder;
    }
    /// <inheritdoc/>
    public void HideAjax() {
      if (Interlocked.Decrement(ref loadCount) == 0) {
        form.UseWaitCursor = false;
        form.Cursor = Cursors.Default;
      }
    }

  }
}
